package com.kun.base.ui

import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.kun.base.BaseApplication

/**
 * baseActivity
 * 实现功能 activity栈，入栈，出栈操作
 * 点击非输入框空白区域隐藏键盘
 * 获取 ViewModel
 *
 *  @author : Kun
 *  @date : 2021/4/13
 *  @time : 16:57
 */
open class BaseActivity : AppCompatActivity() {
    /**
     * 屏蔽home建标志
     */
    val FLAG_HOMEKEY_DISPATCHED = -0x80000000

    private var mActivityProvider: ViewModelProvider? = null
    private var mApplicationProvider: ViewModelProvider? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.setFlags(FLAG_HOMEKEY_DISPATCHED, FLAG_HOMEKEY_DISPATCHED)
        ActivityStack.push(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        ActivityStack.pop(this)
    }

    /**
     * 获取activity级 ViewModel
     * @param modelClass viewModel
     * @param <T>
     * @return
     */
    fun <T : ViewModel> getActivityScopeViewModel(modelClass: Class<T>): T {
        if (mActivityProvider == null) {
            mActivityProvider = ViewModelProvider(this)
        }
        return mActivityProvider!![modelClass]
    }

    /**
     * 获取app级 ViewModel
     * @param modelClass viewModel
     * @param <T>
     * @return
     */
    fun <T : ViewModel> getApplicationScopeViewModel(modelClass: Class<T>): T {
        if (mApplicationProvider == null) {
            mApplicationProvider =
                ViewModelProvider(application as BaseApplication, getAppFactory(this))
        }
        return mApplicationProvider!![modelClass]
    }

    /**
     * 获取application级别的 ViewModelProvider.Factory
     */
    fun getAppFactory(activity: Activity): ViewModelProvider.Factory {
        val app = checkApplication(activity)
        return ViewModelProvider.AndroidViewModelFactory.getInstance(app)
    }

    /**
     * 检查activity绑定的application
     */
    private fun checkApplication(activity: Activity): Application {
        return activity.application
            ?: throw IllegalStateException(
                "Your activity/fragment is not yet attached to "
                        + "Application. You can't request ViewModel before onCreate call."
            )
    }


    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
//            if(Build.VERSION.SDK_INT<=28){
            //小米10系统上会出错？？？
            val v = currentFocus
            if (isShouldHideKeyboard(v, ev)) {
                val imm =
                    getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.hideSoftInputFromWindow(
                    v!!.windowToken,
                    InputMethodManager.HIDE_NOT_ALWAYS
                )
            }
            //            }
        }
        return super.dispatchTouchEvent(ev)
    }

    /**
     * 实现功能 点击空白区域隐藏软键盘
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘
     */
    private fun isShouldHideKeyboard(v: View?, event: MotionEvent): Boolean {
        return if (v != null && v is EditText) {
            val l = intArrayOf(0, 0)
            v.getLocationInWindow(l)
            val left = l[0]
            val top = l[1]
            val bottom = top + v.getHeight()
            val right = left + v.getWidth()
            // 点击位置如果是EditText的区域，忽略它，不收起键盘。
            !(event.x > left && event.x < right && event.y > top && event.y < bottom)
        } else {
            false
        }
    }
}